package org.shiro.demo.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.joda.time.DateTime;
import org.shiro.demo.entity.ResponseResult;
import org.shiro.demo.entity.User;
import org.shiro.demo.service.IBaseService;
import org.shiro.demo.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mob.sms.MobClient;
import com.utils.AESUtil;

/**
 * mob手机短信验证。
 * 
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/mob")
public class MobController {
	@Resource(name = "userService")
	private IUserService userService;

	@Resource(name = "baseService")
	private IBaseService baseService;

	/**
	 * 手机登陆
	 * 
	 * @deprecated
	 * 
	 * @param user
	 * @param session
	 * @param request
	 * @param reponse
	 * @return
	 */
	@RequestMapping(value = "/xxxxxxxxlogin")
	public @ResponseBody Object smslogin(String type, String phone, String code, HttpSession session, HttpServletRequest request, HttpServletResponse reponse) {
		// 对比mob 看看是否 status=200
		if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
			return new ResponseResult(0, "手机号或者验证码不能为空", "");
		}

		try {
			// 查查看 是否 验证码 过期了..查询mob服务器
			MobClient client = new MobClient("https://api.sms.mob.com/sms/verify");

			String result = client.post(getRequestBody(type, phone, code));
			JSONObject jb = JSONObject.fromObject(result);
			int returnCode = (Integer) jb.get("status");
			if (returnCode != 200) {
				System.out.println(phone + "--mob找回密码回馈" + returnCode);
				return new ResponseResult(0, "验证码无效" + returnCode, "");
			}

		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseResult(0, "mob 服务器返回有错误，稍后再试", "");
		}
		// 能走到这一步，说明验证成功了。

		// 获取当前的Subject
		Subject curUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken("mob;" + phone, "1");
		token.setRememberMe(true);
		try {
			// 在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
			// 每个Realm都能在必要时对提交的AuthenticationTokens作出反应
			// 所以这一步在调用login(token)方法时,它会走到ShiroDbRealm.doGetAuthenticationInfo()方法中
			System.out.println("1");
			curUser.login(token);
			System.out.println("2");
			// 添加信息
			/*
			 * if (null != curUser) { Session shiro_session =
			 * curUser.getSession(); if (null != shiro_session) {
			 * shiro_session.setAttribute(Keys.CURRENT_USER, user); } }
			 */
			System.out.println("3");
			System.out.println(request.getSession().getId());
			reponse.addHeader("id", request.getSession().getId());
			reponse.addHeader("Cookie", request.getHeader("Cookie"));
			User user = userService.getByPhone(phone);
			ResponseResult rr = new ResponseResult(1, request.getSession().getId(), user);
			// / 走到这一步， code 要重置.设置为空
			return rr;
		} catch (AuthenticationException e) {
			// 通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
			token.clear();
			return new ResponseResult(0, "登录失败", "");// 登录失败，返回空
		}
	}

	/**
	 * 手机 注册
	 * 
	 * 
	 * @param user
	 * @param session
	 * @param request
	 * @param reponse
	 * @return
	 */
	@RequestMapping(value = "/smsregister")
	public @ResponseBody Object smsregister(String type, String phone, String code, String password, HttpSession session, HttpServletRequest request, HttpServletResponse reponse) {
		String deString = null;
		try {
			deString = AESUtil.Decrypt(password);
			password = deString;
			if (deString == null) {
				return new ResponseResult(0, "密码解密失败", null);// 注册失败，返回空
			}
			if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code) || StringUtils.isEmpty(password)) {
				return new ResponseResult(0, "手机号或者验证码不能为空", "");
			}
			// 密码 不能再简单
			if (password.length() <= 4) {
				return new ResponseResult(0, "密码太简单", "");
			}
			if (password.length() > 16) {
				return new ResponseResult(0, "密码太长，不能超过15位", "");
			}

			if (userService.getByPhone(phone) != null) {
				return new ResponseResult(0, "用户已存在", "");
			}

			// 查查看 是否 验证码 过期了..查询mob服务器
			MobClient client = new MobClient("https://api.sms.mob.com/sms/verify");

			String result = client.post(getRequestBody(type, phone, code));
			JSONObject jb = JSONObject.fromObject(result);
			int returnCode = (Integer) jb.get("status");
			if (returnCode != 200) {
				System.out.println(phone + "--mob回馈" + returnCode);
				return new ResponseResult(0, "验证码无效" + returnCode, "");
			}

		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseResult(0, "mob 服务器返回有错误，稍后再试", "");
		}
		try {
			// 添加信息
			User user = new User();

			user.setPassword(deString);// 对password 进行解密。
			user.setPhone(phone);
			user.setUsername(phone);
			user.setName(phone);
			user.setCreateTime(new Date());
			user.setBirthday(new DateTime(2000, 1, 1, 0, 0, 0).toDate());//修补bug
			System.out.println("--注册成功");
			baseService.save(user);
			ResponseResult rr = new ResponseResult(1, "注册成功", user);
			// / 走到这一步， code 要重置.设置为空
			return rr;
		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseResult(0, "注册失败", "");// 注册失败，返回空
		}
	}

	/**
	 * 手机 找回密码
	 * 
	 * 
	 * @param user
	 * @param session
	 * @param request
	 * @param reponse
	 * @return
	 */
	@RequestMapping(value = "/getback")
	public @ResponseBody Object getback(String type, String phone, String code, String password, HttpSession session, HttpServletRequest request, HttpServletResponse reponse) {
		String deString = null;
		try {
			System.out.println("打印密码+"+password);
			deString = AESUtil.Decrypt(password);
			password = deString;
			if (deString == null) {
				return new ResponseResult(0, "密码解密失败", null);// 注册失败，返回空
			}
			if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code) || StringUtils.isEmpty(password)) {
				return new ResponseResult(0, "手机号或者验证码或者密码不能为空", "");
			}
			// 密码 不能再简单
			if (password.length() <= 4) {
				return new ResponseResult(0, "密码太简单", "");
			}
			if (password.length() > 16) {
				return new ResponseResult(0, "密码太长，不能超过15位", "");
			}

			// 查查看 是否 验证码 过期了..查询mob服务器
			MobClient client = new MobClient("https://api.sms.mob.com/sms/verify");

			String result = client.post(getRequestBody(type, phone, code));
			JSONObject jb = JSONObject.fromObject(result);
			int returnCode = (Integer) jb.get("status");
			if (returnCode != 200) {
				System.out.println(phone + "--mob回馈" + returnCode);
				return new ResponseResult(0, "验证码无效" + returnCode, "");
			}

		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseResult(0, "mob 服务器返回有错误，稍后再试", "");
		}

		try {
			// 添加信息
			User user = userService.getByPhone(phone);
			System.out.println("--找回密码成功");
			user.setPassword(password);
			baseService.update(user);
			user.setPassword("");
			ResponseResult rr = new ResponseResult(1, "重置密码成功", user);
			// / 走到这一步， code 要重置.设置为空
			return rr;
		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseResult(0, "重置失败", "");// 登录失败，返回空
		}
	}

	enum SmsType {
		Login, Register, Getback
	}

	private String getRequestBody(String type, String phone, String code) {
		Map<String, String> map = new HashMap<String, String>();
		if (type != null && type.equals("ios")) {
			System.out.println("--ios验证");
			map.put("appkey", "6cb9f8457c88");

		} else {
			map.put("appkey", "646c79aecc19");

		}
		map.put("phone", phone);
		map.put("zone", "86");
		map.put("code", code);

		StringBuilder builder = new StringBuilder();
		for (String key : map.keySet()) {
			builder.append(key);
			builder.append("=");
			builder.append(map.get(key) + "&");
		}
		return builder.toString().substring(0, builder.length() - 1);

	}

}
